#include "EventLoop.h"
#include "Poller.h"
#include "Channel.h"
#include "TaskQueue.h"
#include <cassert>
#include <memory>

namespace GiSo {

EventLoop::EventLoop(int threadNum):m_ThreadPool(threadNum),m_Poller() {
    m_MainQueue = std::make_shared<TaskQueue>();
}

EventLoop::~EventLoop() {
    // 清理资源
}

void EventLoop::Run() {
    m_Running = true;
    ChannelList activeChannels; // raw pointer，因为epoll_wait返回的是原始指针
    while (m_Running) {
        // 调用 Poller 监听事件
        activeChannels.clear();
        int numEvents = m_Poller.Poll(kPollTimeoutMs, activeChannels);

        // 回调事件
        for (auto channel : activeChannels) {
            channel->HandleEvent();
        }

        // 处理任务队列中的任务
        while(!m_MainQueue->Empty()) {
            auto task = m_MainQueue->PopFront();
            if (task) {
                (*task)();
            }
        }
    }
}

void EventLoop::UpdateChannel(Channel* channel) {
    m_Poller.UpdateChannel(channel);
}

void EventLoop::RemoveChannel(Channel* channel) {
    m_Poller.RemoveChannel(channel);
}


} // namespace GiSo